<template>
  <div style="width: 24%; margin: 10px auto; order-radius: 20px; ">
    <div style="background-color: white; padding: 10px; border: 1px solid #ccc; border-radius: 10px; height: 525px; ">
      <!--  列表标题-->
      <div style="margin: 10px 0; color: SlateBlue; font-size: 16px">
        <el-icon style="vertical-align: middle;"><UserFilled/></el-icon>
        <b style="padding-left: 10px">好友列表 </b>
      </div>

      <!--  好友列表-->
      <div style="flex: 1; color: SlateBlue; border: 1px solid #ccc;  height: 450px;  font-size: 10px;overflow-y: scroll; border-radius: 3%">
        <!--  动态获取好友-->
        <div style="padding: 6px; border: 1px solid #ccc; " v-for="(item,index) in state.addfriends" :key="index" :class="{'left-list' : active == item.id}" @click="startCall(item)" >
          <div style="display:flex;" >
            <img style="width: 40px; height: 40px; margin-right: 20px; border-radius: 50%"
                 :src="item.user.avatar"
                 alt="">
            <div style="flex: 1; line-height: 20px">
              <div style="font-weight: bold"> {{ item.user.username }} </div>
              <div style="font-size: 12px; color: #999">{{ item.user.address}}</div>
            </div>

          </div>
        </div>
      </div>

    </div>
  </div>

    <!-- 3 好友聊天-->
    <div style="width: 59%; margin: 10px auto">
      <div ref="divRef"  style="background-color: rgb(247,247,247); padding: 20px; border: 1px solid #ccc; border-radius: 10px; height: 400px; overflow-y: scroll;">
        <div v-for="(item,index) in state.message" :key="index" >
          <el-scrollbar>
            <!-- 3.1 别人给我发的消息 -->
            <div style="display: flex; margin: 20px 0;" v-if="item.toId ===  user.id">
              <!-- 3.1.1 点击头像所显示的框框 -->
              <el-popover
                  placement="top-start"
                  :width="100"
                  trigger="hover"
              >
                <!-- 3.1.2 弹出框类容 -->
                <div style="line-height: 20px">
                  <div style="font-size: 16px">{{item.user.namex}}</div>
                  <div style="font-size: 12px;">{{item.user.sign}}</div>
                </div>
                <!-- 3.1.3头像 -->
                <template #reference>
                  <img :src="item.user.avatar" alt="" style="width: 30px; height: 30px; border-radius: 50%; margin-right: 10px">
                </template>
              </el-popover>
              <!-- 3.1.4 聊天内容 -->
              <div style="line-height: 30px; background-color: aliceblue; padding: 0 10px; width:fit-content; border-radius: 10px">{{item.contents}}</div>
            </div>

            <!-- 3.2 我给别人发的消息  justify-content: flex-end：靠右显示-->
            <div style="display: flex; justify-content: flex-end; margin: 20px 0;" v-else>
              <div style="line-height: 30px; background-color: lightyellow; padding: 0 10px; width:fit-content; border-radius: 10px;">{{item.contents}}</div>
              <el-popover
                  placement="top-start"
                  :width="100"
                  trigger="hover"
              >
                <template #reference>
                  <img :src="item.user.avatar" alt="" style="width: 30px; height: 30px; border-radius: 50%; margin-left: 10px">
                </template>
                <div style="line-height: 20px">
                  <div style="font-size: 16px">{{item.user.namex}}</div>
                  <div style="font-size: 12px;">{{item.user.sign}}</div>
                </div>
              </el-popover>
            </div>

          </el-scrollbar>
        </div>
      </div>

      <!-- 3 聊天输入框 第三方插件 -->
      <div style="margin: 10px 0; width: 100%;">
        <V3Emoji default-select="recent" :recent="true" :options-name="optionsName" :keep="true"  :textArea="true" size="mid" v-model="text" />
        <div style="text-align: right">
          <el-button @click="send" type="primary">发送</el-button>
        </div>
      </div>

      <router-view></router-view>


    </div>
</template>

<script setup>
import {nextTick, onMounted, ref, reactive} from "vue";
import {useUserStore} from "@/stores/user";
import V3Emoji from 'vue3-emoji'
import 'vue3-emoji/dist/style.css'
import {ElMessage} from "element-plus";
import request from "@/utils/request";
import {onBeforeRouteUpdate, useRoute, useRouter} from 'vue-router'
const optionsName = {
  'Smileys & Emotion': '笑脸&表情',
  'Food & Drink': '食物&饮料',
  'Animals & Nature': '动物&自然',
  'Travel & Places': '旅行&地点',
  'People & Body': '人物&身体',
  Objects: '物品',
  Symbols: '符号',
  Flags: '旗帜',
  Activities: '活动'
}

let route = useRoute();
const query = reactive({to:'',pageNum:1,pageSize:10})
const userStore = useUserStore()
const user = userStore.getUser
const text = ref('')
const divRef = ref()          // 聊天框的引用。发送消息后，需要把滚动条滚动到最新位置，需要用到这个引用
const messages = ref([]) // 聊天输入的内容
let fid = ref('')
const active = ref('')

const state = reactive({
  addfriends: [],
  message:[]
})

// 获取当前用户所有好友
const load = () => {
  request.get('/friends/hot', {
    params: {
      pageNum: 1,
      pageSize: 20
    }
  }).then(res => {
    state.addfriends = res.data.records
    console.log(res.data.records)
  })
}

load()

// 点击对话，对话框变色
const startCall = (res)=>{
  active.value = res.id
  fid =  res.fid
  getMessage(res.fid)
  router.push({ path:'chat',query:{fid:res.fid}})


}

// 储存对话框的聊天消息
const send = () =>{
  messages.value = []

  if(fid === undefined){
    ElMessage.error("请选择好友开始聊天")
  }else {
    messages.value.push({fromId: user.id, toId: fid , type: 1, contents: text.value})
    // 把新聊天消息存到数据库
    request.request({
      url: '/message',
      method: 'post',
      data: messages.value
    }).then(res => {
      if (res.code === '200') {
        // 获取聊天信息
        getMessage(fid)
        // 不传 message 因为，当用户1给用户2发消息时，通过 websocket 给2推消息，推了之后，
        // 即调用 send 方法之后，send 是先将信息存入数据库再重新获取消息，这样可以直接拿到数据了
        socket.send({from: user.id, to: fid, type: 2})

      } else {
        ElMessage.error(res.msg)
      }
    })
  }

  // 清空输入框
  text.value = ''

}

// 页面滚动到最新位置的函数
const scrollBottom = () => {
  // 数据渲染通过v-if， scrollBottom函数触发时，页面的DOM不一定渲染好了
  // 等到页面元素出来之后再去滚动
  nextTick(() => {
    if(  divRef.value ){
      divRef.value.scrollTop = divRef.value.scrollHeight
    }

  })
}

onBeforeRouteUpdate((to)=>{
  fid = to.query.fid
  // getuid()
  console.log(fid)
  getMessage(fid);
})

onMounted(()=>{
  console.log(fid)
  getuid()
})

const getuid = ()=>{
  console.log(fid)
  query.to = route.query.fid
  fid = route.query.fid
  getMessage(fid);
}

const getMessage = (fid) =>{
  request.get('/message/hot', {
    params: {
      fid: fid,
      pageNum: 1,
      pageSize: 300
    }
  }).then(res => {
    state.message = res.data.records
    scrollBottom()
    console.log(res.data.records)

  })
}
// -----------------------------------------------------
import socket from "../utils/websocket.ts"
import {websocketStore} from "@/stores/websokcet"
import router from "@/router";

const web = websocketStore()

web.$subscribe((mutations, state) => {
  console.log(state.msg) // {"type":2,"uuid":"1a5795ab-6238-4896-a574-9fde49d86df5"}
  let msg = JSON.parse(state.msg);
  if (msg.type === 2){
    getMessage(fid)
  }
})

const loginWebsocket = ()=>{
  Promise.resolve().then(()=>{
    socket.init()
  }).then(()=>{
    socket.send({uid: user.id, type: 1})
  })
}

onMounted(()=>{
  loginWebsocket()
})
</script>

<style scoped>
.left-list{
  background-color: #eaeaea;
}
</style>